/*
 * @Description:
 * @Date: 2022-11-07 16:40:18
 * @LastEditors: czp
 * @LastEditTime: 2023-04-14 16:27:27
 */
import { ElMessageBoxOptions } from "element-plus";
import NProgress from "nprogress";

/**
 * 消息弹窗
 * @param options
 * @returns
 */
export const MsgBox = (options: ElMessageBoxOptions) => {
	return new Promise(resolve => {
		ElMessageBox.confirm(options.message, {
			...options
		})
			.then(() => {
				resolve("OK");
			})
			.catch(() => {
				resolve("cancel");
			});
	});
};

let loadingInstance: ReturnType<typeof ElLoading.service>;
const startLoading = () => {
	loadingInstance = ElLoading.service({
		fullscreen: true,
		lock: true,
		text: "Loading",
		background: "rgba(0, 0, 0, 0.7)"
	});
};

/**
 * 隐藏 loading 提示框
 */
const endLoading = () => {
	loadingInstance.close();
};

// 那么 showFullScreenLoading() tryHideFullScreenLoading() 要做的事就是将同一时刻的请求合并。
// 声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
// 调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0;
export const showFullScreenLoading = () => {
	if (needLoadingRequestCount === 0) {
		startLoading();
	}
	needLoadingRequestCount++;
};

export const tryHideFullScreenLoading = () => {
	if (needLoadingRequestCount <= 0) return;
	needLoadingRequestCount--;
	if (needLoadingRequestCount === 0) {
		endLoading();
	}
};

export const Progress = NProgress.configure({
	easing: "ease", // 动画方式
	speed: 500, // 递增进度条的速度
	showSpinner: true, // 是否显示加载ico
	trickleSpeed: 200, // 自动递增间隔
	minimum: 0.3 // 初始化时的最小百分比
});
